<template>
  <div class="page-main">
    <el-container style="height: 100%; padding: 20px;">
      <!-- 左侧配置 -->
      <el-aside width="230px" style="border-right: 1px solid #eee; padding-right: 20px">
        <el-form label-position="left" :label-width="'80px'">
          <!-- 矿山 -->
          <el-form-item label="矿山">
            <!-- <el-select v-model="selectedMineId" placeholder="请选择矿山" style="width: 100%">
              <el-option v-for="mine in mines" :key="mine.id" :label="mine.name" :value="mine.id" />
            </el-select> -->
            <DataSelect ref="kuangshan_select" table="Department" class="fr" placeholder="请选择矿山"
              :filter="{ _Type: Enums.Department_Type.矿山 }" v-model:id="selectedMineId"
              ></DataSelect>
          </el-form-item>

          <!-- 钢丝绳组 -->
          <el-form-item label="钢丝绳组">
            <!-- <el-select v-model="selectedRopeSetId" placeholder="请选择钢丝绳组" style="width: 100%">
              <el-option v-for="set in currentRopeSets" :key="set.id" :label="set.name" :value="set.id" />
            </el-select> -->
            <DataSelect ref="ropeGroupRef" table="UsingWirerope" action="GetSearch"  orderBy="[x].[UsingWireropeID]" class="fr" placeholder="请选择钢丝绳组"
              :filter="ropeGroupFilter" :isLoadingData="!!selectedMineId" v-model:id="selectedRopeSetId" v-model:obj="selectedRopeSetObj"
              ></DataSelect>
          </el-form-item>

          <el-divider />

          <!-- 最大值、最小值、平均值 -->
          <el-form-item label="最大值">
            <el-input :model-value="data?.maxValue" readonly size="small" />
          </el-form-item>
          <el-form-item label="最小值">
            <el-input :model-value="data?.minValue" readonly size="small" />
          </el-form-item>
          <el-form-item label="平均值">
            <el-input :model-value="data?.avgValue" readonly size="small" />
          </el-form-item>
        </el-form>

        <!-- 启停按钮 -->
        <el-button :type="isRunning ? 'danger' : 'primary'" @click="togglePolling" style="width: 100%" size="large">
          {{ isRunning ? '停止读取' : '开始读取' }}
        </el-button>
      </el-aside>

      <!-- 右侧数据展示 -->
      <el-main style="display: flex; flex-direction: column; height: 100%;">
        <!-- 实时趋势图 -->
        <div class="chart-wrapper" style="flex: 1; display: flex; flex-direction: column;">
          <RealtimeTensionChart ref="tensionChartRef" :data="dataForChart" />
        </div>

        <!-- 差值输入框 -->
        <div class="diff-row-full" v-show="hasDiffValues">
          <label class="diff-label">差值：</label>
          <div class="diff-inputs" :style="{ gridTemplateColumns: `repeat(${diffCount}, 1fr)` }">
            <el-input v-for="(diff, index) in diffValues" :key="index" :model-value="diff" readonly size="small" />
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import Enums from "@/gx/Enums";

// import { ref, computed, onUnmounted, watch } from 'vue'
import RealtimeTensionChart from '@/views/ZhangLi/RealtimeTensionChart.vue'

// 数据结构定义
interface Mine {
  id: string
  name: string
  ropeSets: RopeSet[]
}

interface RopeSet {
  id: number
  name: string
  ropeCount: number
}

interface RopeData {
  realtimeValues: number[] // 每根钢丝绳当前张力值（一维数组）
  diffValues: number[]      // 每根钢丝绳与平均值的差值
  maxValue: number
  minValue: number
  avgValue: number
}

// 当前选中
const selectedMineId = ref<number | null>(null)
const selectedRopeSetId = ref<number | null>(null)
const currentRopeCount = ref<number | null>(null)
const isRunning = ref<boolean>(false)

// 差值
const hasDiffValues = computed(() => {
  return !!data.value && Array.isArray(data.value.diffValues) && data.value.diffValues.length > 0
})

const diffCount = computed(() => {
  return hasDiffValues.value ? data.value!.diffValues.length : 0
})

const diffValues = computed(() => {
  return hasDiffValues.value ? data.value!.diffValues : []
})

// 模拟后端返回的数据
const data = ref<RopeData | null>(null)

function generateMockData(ropeCount: number): RopeData {
  const values = Array.from({ length: ropeCount }, (_, i) => Math.floor(Math.random() * 100) + 50)
  const avg = Number((values.reduce((a, b) => a + b, 0) / values.length).toFixed(2))
  const diffs = values.map(v => Number((v - avg).toFixed(2)))

  return {
    realtimeValues: values,
    diffValues: diffs,
    maxValue: Math.max(...values),
    minValue: Math.min(...values),
    avgValue: avg
  }
}

// 只用于传给图表组件（避免引用污染）
const dataForChart = computed(() => {
  if (!data.value) return null
  return {
    realtimeValues: [...data.value.realtimeValues]
  }
})

// 定时器
let pollingInterval: number | null = null

function togglePolling() {
  if (!selectedRopeSetId.value || currentRopeCount.value <= 0) {
    alert('请先选择钢丝绳组')
    return
  }

  if (isRunning.value) {
    clearInterval(pollingInterval!)
    pollingInterval = null
    isRunning.value = false
  } else {
    // 第一次采集，立即生成初始数据
    fetchData()
    isRunning.value = true
    pollingInterval = setInterval(fetchData, 500)
  }
}

function fetchData() {
  if (!isRunning.value) return

  const newData = generateMockData(currentRopeCount.value)
  data.value = newData
}

const tensionChartRef = ref()

watch(selectedRopeSetId, () => {
  if (isRunning.value) {
    clearInterval(pollingInterval!)
    isRunning.value = false
  }
  data.value = null
  tensionChartRef.value?.clearChart()
})


const ropeGroupRef = ref()
const selectedRopeSetObj = ref<any>(null)
const ropeGroupFilter = computed(() => {
  return selectedMineId.value ? { _DepartmentID: selectedMineId.value } : {}
})

watch(selectedRopeSetObj, (newVal) => {
  if (newVal) {
    currentRopeCount.value = newVal.cnt
    console.log('当前钢丝绳组钢丝绳数:', currentRopeCount.value)
  }
})

watch(selectedMineId, () => {
  if (selectedMineId.value) {
    ropeGroupRef.value?.ClearList()
    nextTick().then(() => {
      ropeGroupRef.value?.GetList()
    })
  } else {
    ropeGroupRef.value?.ClearList()
    selectedRopeSetId.value = null
    selectedRopeSetObj.value = null
    currentRopeCount.value = null
  }
})

// 页面加载时默认选第一个矿山
onMounted(() => {
  // if (mines.value.length > 0) {
  //   selectedMineId.value = mines.value[0].id
  //   if (mines.value[0].ropeSets.length > 0) {
  //     selectedRopeSetId.value = mines.value[0].ropeSets[0].id // 自动选第一个钢丝绳组
  //   }
  // }
})

// 页面加载默认值
onUnmounted(() => {
  if (pollingInterval) {
    clearInterval(pollingInterval)
  }
})

</script>

<style scoped>
.el-main {
  padding: 0;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chart-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.diff-row-full {
  display: flex;
  align-items: center;
  gap: 10px;
  /* margin-bottom: 10px; */
  /* margin-top: 20px; */
  margin: 20px 0 10px 0;
}

.diff-label {
  flex-shrink: 0;
  width: 60px;
  text-align: right;
  font-size: 14px;
}

.diff-inputs {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(60px, 1fr));
  gap: 5px;
  overflow-x: auto;
  padding-bottom: 4px;
  flex-grow: 1;
}

/* 可选美化 */
.diff-inputs ::v-deep(.el-input__inner) {
  /* padding: 0 5px; */
  text-align: center;
  /* background-color: #f9fafc; */
  /* border: none; */
}
</style>